from typing import *


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def kthLargestPerfectSubtree(self, root: Optional[TreeNode], k: int) -> int:
        ls = []

        def f(root, h):
            if root is None:
                return [True, 0, h]
            left = f(root.left, h + 1)
            right = f(root.right, h + 1)
            b = left[0] and right[0] and left[2] == right[2]
            if b:
                ls.append(left[1] + right[1] + 1)
            return [
                b,
                left[1] + right[1] + 1,
                left[2] if left[2] == right[2] else -1,
            ]

        f(root, 0)

        return sorted(ls, reverse=True)[k - 1] if len(ls) >= k else -1
